package efu.nf.like.common.confirm;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author lwj
 * @create 2025-10-15-9:01
 *
 *
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ConfirmCallbackContext {
    /**
     * 注入 RabbitTemplate
     */
    private final RabbitTemplate rabbitTemplate;
    /**
     * 注入所有 ConfirmCallbackService 的实现类
     * 在不同的业务场景调用不同的是实现来处理投递失败的业务逻辑
     */
    private final Map<String, ConfirmCallbackService> confirmCallbackServiceMap;

    /**
     * 统一调用回调处理
     * 在容器初始化时就执行这个方法
     */
    @PostConstruct
    public void confirmCallback(){
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            // 获取失败的消息对象
            ReturnedMessage returnedMessage = correlationData.getReturned();
            // 判断是否正确投递到交换机
            if(ack){
                log.info("消息投递成功：{}", returnedMessage.getExchange());
            }else{
                // 获取业务回调实现类
                ConfirmCallbackService confirmCallbackService = confirmCallbackServiceMap.get(returnedMessage.getReplyText());
                // 执行回调处理
                confirmCallbackService.confirmCallback(returnedMessage.getMessage());
            }
        });
    }
}